

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.ico">
  <link rel="icon" href="/img/favicon.ico">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="Try not to become a man of success but rather try to become a man of value. ">
  <meta name="author" content="kinzun">
  <meta name="keywords" content>
  <meta name="description" content="核能来袭-成员一.类的成员12345678910class 类名:# ⽅方法	def __init__(self, 参数1, 参数2....):		# 属性变量量		self.属性1 = 参数1		self.属性2 = 参数2....	# ⽅方法	def method(self):	pas  在上面代码中__init__和method 都属于类的成员方法. 又称为实例⽅方法. 总之这样的东西需要用">
<meta name="keywords" content="Python">
<meta property="og:type" content="article">
<meta property="og:title" content="Python:面对对象成员(2)">
<meta property="og:url" content="https://kinzun.github.io/2018/09/26/Python面对对象成员(2)/index.html">
<meta property="og:site_name" content="kinzun">
<meta property="og:description" content="核能来袭-成员一.类的成员12345678910class 类名:# ⽅方法	def __init__(self, 参数1, 参数2....):		# 属性变量量		self.属性1 = 参数1		self.属性2 = 参数2....	# ⽅方法	def method(self):	pas  在上面代码中__init__和method 都属于类的成员方法. 又称为实例⽅方法. 总之这样的东西需要用">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://kinzun.github.io/images/python/class/class_member.png">
<meta property="og:updated_time" content="2018-10-25T11:24:37.061Z">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Python:面对对象成员(2)">
<meta name="twitter:description" content="核能来袭-成员一.类的成员12345678910class 类名:# ⽅方法	def __init__(self, 参数1, 参数2....):		# 属性变量量		self.属性1 = 参数1		self.属性2 = 参数2....	# ⽅方法	def method(self):	pas  在上面代码中__init__和method 都属于类的成员方法. 又称为实例⽅方法. 总之这样的东西需要用">
<meta name="twitter:image" content="https://kinzun.github.io/images/python/class/class_member.png">
  
  <title>Python:面对对象成员(2) - kinzun</title>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css">


  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css">
  <link rel="stylesheet" href="/lib/hint/hint.min.css">

  
    
    
      
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css">
    
  

  
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css">
  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">

<link rel="stylesheet" href="/css/main.css">

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"kinzun.github.io","root":"/","version":"1.8.12","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname"}},"search_path":"/local-search.xml"};
  </script>
  <script src="/js/utils.js"></script>
  <script src="/js/color-schema.js"></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>kinzun</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Python:面对对象成员(2)">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2018-09-26 19:40" pubdate>
        2018年9月26日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      4.4k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      14 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Python:面对对象成员(2)</h1>
            
            <div class="markdown-body">
              <h3 id="核能来袭-成员"><a href="#核能来袭-成员" class="headerlink" title="核能来袭-成员"></a>核能来袭-成员</h3><h4 id="一-类的成员"><a href="#一-类的成员" class="headerlink" title="一.类的成员"></a>一.类的成员</h4><figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python"><span class="hljs-class"><span class="hljs-keyword">class</span> 类名:</span><br><span class="hljs-comment"># ⽅方法</span><br>	<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, 参数<span class="hljs-number">1</span>, 参数<span class="hljs-number">2.</span>...)</span>:</span><br>		<span class="hljs-comment"># 属性变量量</span><br>		self.属性<span class="hljs-number">1</span> = 参数<span class="hljs-number">1</span><br>		self.属性<span class="hljs-number">2</span> = 参数<span class="hljs-number">2</span><br>....<br>	<span class="hljs-comment"># ⽅方法</span><br>	<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">method</span><span class="hljs-params">(self)</span>:</span><br>	pas<br></code></pre></div></td></tr></table></figure>
<blockquote>
<p>在上面代码中<code>__init__</code>和<code>method</code> 都属于类的成员方法. 又称为实例⽅方法. 总之这样的东西需要用对象来访问. ⽽而上方的<code>self</code> .属性1 = 参数1 这个代码的含义是给对象设置属性信息. 含义是这个对象的xxx属性是xxxx. 这种东西又被称之为成员变量量或者实例变量量, 再或者被称之为字段. 都是一个意思.</p>
</blockquote>
<figure class="highlight"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python">   Province+---------^-------------------------+<br>          ^----------+                         |<br>+-----------------+  |                         |<br>|                 |  +-----------------+       |obj=Province(北 京 )<br>| +---------------+                    |       |<br>| |country=中   国 |-----&gt;#静 态 字 段        |    --+-v------------------<br>| +---------------+                    |     |  name = 北 京           |<br>|                 |                    |     |                         |<br>|                 |                    |     +-----------------------+<br>+-----------------+                    |     | 类 对 象 指 针             |<br>|                 |                    |     |                       |<br>|                 |                    |     +-----------------------+<br>|                 |                    |<br>|                 |                    |        obj2 = Province(河 北 省 )<br>|                 |                    |<br>| def __init__(...)                    |      +------------------------+<br>|     ...         |                    |      |  name = 河 北 省          |<br>| def func(...)   |                    |      |                        |<br>|     ..          |                    +^-----+ +----------------------+<br>|                 |                           |  类 对 象 指 针           |<br>|                 |                           |                        |<br>|                 |                           +------------------------+<br>|                 |<br>|                 |<br>|                 |<br>|                 |<br>+-----------------+<br></code></pre></div></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>:</span><br>    country = <span class="hljs-string">"中国"</span>  <br>    <span class="hljs-comment">#类变量. 不属于对象, 对象可以访问.</span><br>    <span class="hljs-comment">#静态变量(静态字段)</span><br><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, name, num, gender, birthday)</span>:</span><br>        <span class="hljs-comment"># 成员变量(实例变量)</span><br>        self.name = name<br>        self.num = num<br>        self.gender = gender<br>        self.birthday = birthday<br><br>    <span class="hljs-comment"># 对象来访问（成员方法）（实例方法）</span><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">marray</span><span class="hljs-params">(self, duifang)</span>:</span><br>        print(<span class="hljs-string">"人会结婚%s"</span> % duifang)  <span class="hljs-comment">#普通字段</span><br><br>alex = Person(<span class="hljs-string">"李连杰"</span>, <span class="hljs-number">10086</span>, <span class="hljs-string">"男"</span>, <span class="hljs-string">"昨天"</span>)<br>alex.country = <span class="hljs-string">"澳大利亚"</span> <span class="hljs-comment"># 注意。 这里和类变量没由一毛钱关系, 给alex单独加一个属性叫country = ”澳大利亚“</span><br><br>wusir = Person(<span class="hljs-string">"12"</span>, <span class="hljs-number">10010</span>, <span class="hljs-string">"女"</span>, <span class="hljs-string">"今天"</span>)<br><br>print(alex.country) <span class="hljs-comment"># 澳大利亚 # 拿到的是自己的。成员实例变量 字段</span><br>print(wusir.country) <span class="hljs-comment"># 中国</span><br>print(Person.country)   <span class="hljs-comment"># 中国</span><br><br>Person.country<span class="hljs-comment"># 直接访问静态字段</span><br><br><span class="hljs-comment"># 总结：类变量，用类名去操作. 规范.</span><br><br><span class="hljs-comment">#静态字段在内存中只保存一份</span><br><span class="hljs-comment">#普通字段在每个对象中都要保存一份</span><br></code></pre></div></td></tr></table></figure>
<blockquote>
<p>应用场景： 通过类创建对象时，如果每个对象都具有相同的字段，那么就使用静态字段</p>
</blockquote>
<h4 id="二-类的成员-方法"><a href="#二-类的成员-方法" class="headerlink" title="二.类的成员-方法"></a>二.类的成员-方法</h4><ol>
<li><p>成员方法(实例方法)</p>
</li>
<li><p>静态方法</p>
</li>
<li><p>类方法</p>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Computer</span>:</span><br><span class="hljs-comment"># 实例方法(成员方法)</span><br>	<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">play</span><span class="hljs-params">(self)</span>:</span><br>		print(<span class="hljs-string">"我的电脑可以玩⼉"</span>)<br>c = Computer()<br>c.play() <span class="hljs-comment"># 对象直接去调用实例方法</span><br></code></pre></div></td></tr></table></figure>
<blockquote>
<ol>
<li>成员方法(实例方法：由<strong>对象</strong>调用；至少一个<code>self</code> 参数；执行普通方法时，自动将调用该方法的<strong>对象</strong>赋值给<strong>self</strong>；</li>
<li>类方法：由<strong>类</strong>调用； 至少一个<code>cls</code> 参数；执行类方法时，自动将调用该方法的<strong>类</strong>复制给<strong>cls</strong>；</li>
<li>静态方法：由<strong>类</strong>调用；无默认参数；</li>
</ol>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>:</span><br><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span><br>        <span class="hljs-keyword">pass</span><br>    <span class="hljs-comment"># 实例方法需要传递类的对象 self</span><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">think</span><span class="hljs-params">(self)</span>:</span><br>        print(<span class="hljs-string">"人能思考"</span>)<br><br>    <span class="hljs-comment"># 静态方法不需要传递对象或者类</span><br><span class="hljs-meta">    @staticmethod # 静态方法</span><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">jisuan</span><span class="hljs-params">(a, b)</span>:</span><br>        print(<span class="hljs-string">"我来过这里"</span>)<br>        <span class="hljs-keyword">return</span> a + b<br><br>    <span class="hljs-comment"># 类方法: 第一个参数传递的是类名</span><br><span class="hljs-meta">    @classmethod</span><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">clsMethod</span><span class="hljs-params">(cls)</span>:</span> <span class="hljs-comment"># cls表示的类</span><br>        p = cls() <span class="hljs-comment"># 可以动态的创建对象.</span><br>        print(<span class="hljs-string">"我是一个类方法"</span>, p)<br><br><br>p = Person()<br>p.think()<br><br>Person.think(p)<br><br><span class="hljs-comment"># 静态方法的调用：</span><br><br>c = Person.jisuan(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>) <span class="hljs-comment">#  类名可以访问</span><br>print(c)<br><br>p = Person()<br>d = p.jisuan(<span class="hljs-number">3</span>, <span class="hljs-number">5</span>) <span class="hljs-comment"># 用对象也可以访问</span><br>print(d)<br><br><span class="hljs-comment"># 记住, 静态的内容用类名访问</span><br><br><span class="hljs-comment">#类方法的调用</span><br><br>Person.clsMethod() <span class="hljs-comment"># 类方法默认第一个参数接收的是类名</span><br></code></pre></div></td></tr></table></figure>
<blockquote>
<p><strong>相同点：</strong>对于所有的方法而言，均属于类（非对象）中，所以，在内存中也只保存一份。</p>
<p><strong>不同点：</strong>方法调用者不同、调用方法时自动传入的参数不同。</p>
</blockquote>
</li>
</ol>
<h4 id="三-属性"><a href="#三-属性" class="headerlink" title="三.属性"></a>三.属性</h4><p><img src="/images/python/class/class_member.png" srcset="/img/loading.gif" lazyload alt></p>
<p>那么属性就非常简单了，因为Python中的属性其实是<strong>成员方法</strong>的变种。</p>
   <figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python"><br><br>​```python<br><span class="hljs-comment"># ############### 定义 ###############</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>:</span><br><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">func</span><span class="hljs-params">(self)</span>:</span><br>        <span class="hljs-keyword">pass</span><br><br>    <span class="hljs-comment"># 定义属性</span><br><span class="hljs-meta">    @property</span><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">prop</span><span class="hljs-params">(self)</span>:</span><br>        <span class="hljs-keyword">pass</span><br><span class="hljs-comment"># ############### 调用 ###############</span><br>foo_obj = Foo()<br><br>foo_obj.func()<br>foo_obj.prop   <span class="hljs-comment">#调用属性</span><br>注意:<br><span class="hljs-number">1.</span> 方法参数只能有一个self<br><span class="hljs-number">2.</span> 方法上方要写@property<br><span class="hljs-number">3.</span> 调⽤用的时候, 我们不需要写括号. 直接当成属性变量来用就可以了了.<br><span class="hljs-number">4.</span> 这种套路路只能取值. 不能设置值<br></code></pre></div></td></tr></table></figure>
<blockquote>
<p>由属性的定义和调用要注意一下几点：</p>
<ul>
<li>定义时，在普通方法的基础上添加  <code>@property</code>  装饰器；</li>
<li>定义时，属性<strong>仅有一个</strong> <code>self</code>  参数</li>
<li>调用时，无需<strong>括号</strong><br>​           方法：foo_obj.func()<br>​           属性：foo_obj.prop</li>
</ul>
</blockquote>
<h4 id="四-私有"><a href="#四-私有" class="headerlink" title="四.私有"></a>四.私有</h4><blockquote>
<p>类的所有成员在上一步骤中已经做了详细的介绍，对于每一个类的成员而言都有两种形式：</p>
</blockquote>
<ul>
<li><p>公有成员，在任何地方都能访问</p>
</li>
<li><p>私有成员，只有在类的内部才能方法,私有成员命名时,前两个字符是 下划线 <code>__foo</code></p>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Tiger</span>:</span><br><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, name, waibiao, qingzhenglianjiedezuofeng, qingfu, money, fangchan)</span>:</span><br>        self.name = name<br>        self.waibiao = waibiao<br>        self.qingzhenglianjiedezuofeng = qingzhenglianjiedezuofeng<br>        self.__qingfu = qingfu<br>        self.__money = money<br>        self.__fangchan = fangchan<br><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">buy</span><span class="hljs-params">(self)</span>:</span><br>        print(<span class="hljs-string">"我有%s"</span> % self.__money)<br>        self.__sel() <br><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__sel</span><span class="hljs-params">(self)</span>:</span><br>        print(<span class="hljs-string">"我要卖掉%s"</span> % self.__fangchan)<br><br><br>lh = Tiger(<span class="hljs-string">"alex"</span>, <span class="hljs-string">"正直"</span>, <span class="hljs-string">"非常刚正不阿, 666"</span>, <span class="hljs-string">"小潘潘"</span>, <span class="hljs-number">10000000000</span>, <span class="hljs-number">5</span>)<br>print(lh.qingzhenglianjiedezuofeng)<br>print(lh.name)<br>print(lh.waibiao)<br>lh.buy()<br><span class="hljs-comment"># lh.__sel()</span><br><span class="hljs-comment"># print(lh.__money)</span><br></code></pre></div></td></tr></table></figure>
<p><strong>私有成员和公有成员的访问限制不同</strong>：</p>
<h6 id="静态字段"><a href="#静态字段" class="headerlink" title="静态字段"></a>静态字段</h6><ul>
<li>公有静态字段：类可以访问；类内部可以访问；派生类中可以访问</li>
<li>私有静态字段：仅类内部可以访问；</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span>:</span><br><br>    name = <span class="hljs-string">"公有静态字段"</span><br><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">func</span><span class="hljs-params">(self)</span>:</span><br>        <span class="hljs-keyword">print</span> C.name<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">D</span><span class="hljs-params">(C)</span>:</span><br><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">show</span><span class="hljs-params">(self)</span>:</span><br>        <span class="hljs-keyword">print</span> C.name<br><br><br>C.name         <span class="hljs-comment"># 类访问</span><br><br>obj = C()<br>obj.func()     <span class="hljs-comment"># 类内部可以访问</span><br><br>obj_son = D()<br>obj_son.show() <span class="hljs-comment"># 派生类中可以访问</span><br></code></pre></div></td></tr></table></figure>
<p>私有静态字段</p>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span>:</span><br><br>    __name = <span class="hljs-string">"公有静态字段"</span><br><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">func</span><span class="hljs-params">(self)</span>:</span><br>        <span class="hljs-keyword">print</span> C.__name<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">D</span><span class="hljs-params">(C)</span>:</span><br><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">show</span><span class="hljs-params">(self)</span>:</span><br>        <span class="hljs-keyword">print</span> C.__name<br><br><br>C.__name       <span class="hljs-comment"># 类访问            ==&gt; 错误</span><br><br>obj = C()<br>obj.func()     <span class="hljs-comment"># 类内部可以访问     ==&gt; 正确</span><br><br>obj_son = D()<br>obj_son.show() <span class="hljs-comment"># 派生类中可以访问   ==&gt; 错误</span><br></code></pre></div></td></tr></table></figure>
<h6 id="普通字段"><a href="#普通字段" class="headerlink" title="普通字段"></a>普通字段</h6><ul>
<li>公有普通字段：对象可以访问；类内部可以访问；派生类中可以访问</li>
<li>私有普通字段：仅类内部可以访问；</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span>:</span><br>    <br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span><br>        self.foo = <span class="hljs-string">"公有字段"</span><br><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">func</span><span class="hljs-params">(self)</span>:</span><br>        <span class="hljs-keyword">print</span> self.foo 　<span class="hljs-comment">#　类内部访问</span><br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">D</span><span class="hljs-params">(C)</span>:</span><br>    <br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">show</span><span class="hljs-params">(self)</span>:</span><br>        <span class="hljs-keyword">print</span> self.foo　＃　派生类中访问<br><br>obj = C()<br><br>obj.foo     <span class="hljs-comment"># 通过对象访问</span><br>obj.func()  <span class="hljs-comment"># 类内部访问</span><br><br>obj_son = D();<br>obj_son.show()  <span class="hljs-comment"># 派生类中访问</span><br></code></pre></div></td></tr></table></figure>
<p>私有普通字段</p>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python"><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span>:</span><br>    <br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span><br>        self.__foo = <span class="hljs-string">"私有字段"</span><br><br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">func</span><span class="hljs-params">(self)</span>:</span><br>        <span class="hljs-keyword">print</span> self.foo 　<span class="hljs-comment">#　类内部访问</span><br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">D</span><span class="hljs-params">(C)</span>:</span><br>    <br>    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">show</span><span class="hljs-params">(self)</span>:</span><br>        <span class="hljs-keyword">print</span> self.foo　＃　派生类中访问<br><br>obj = C()<br><br>obj.__foo     <span class="hljs-comment"># 通过对象访问    ==&gt; 错误</span><br>obj.func()  <span class="hljs-comment"># 类内部访问        ==&gt; 正确</span><br><br>obj_son = D();<br>obj_son.show()  <span class="hljs-comment"># 派生类中访问  ==&gt; 错误</span><br></code></pre></div></td></tr></table></figure>
<p>方法、属性的访问于上述方式相似，即：私有成员只能在类内部使用</p>
<p><em>ps：非要访问私有属性的话，可以通过 对象._类__属性名</em>  </p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Python/">Python</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2018/09/27/ Python约束和异常处理,Md5,日志处理/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Python约束和异常处理,Md5,日志处理</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2018/09/26/Python初始面对对象(1)/">
                        <span class="hidden-mobile">Python:初始面对对象(1)</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                

              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
